package com.rose.doorto.footbathdoor.config;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.rose.doorto.footbathdoor.vo.AlipayVO;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @Author 李庆超
 * @email 1481791489@qq.com
 * @Package：com.rose.doorto.footbathpay
 * @Project：door-to-door
 * @name：AlipayTemplate
 * @date 2024/08/09 2024/8/9:11:10:
 */
@ConfigurationProperties(prefix = "alipay")
@Component
@Data
public class AlipayTemplate {

    // 应用ID,您的APPID，收款账号既是您的APPID对应支付宝账号
    public  String appId = "9021000126614730";

    //商户PID,卖家支付宝账号ID
    public String alipaySellerId = "2088721010044896";

    // 应用私钥，就是工具生成的应用私钥
    public String merchantPrivateKey = "MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCCq1Um0ftNu+nYquF+qO50aQhOtHZMLn6mZbG2l72MoyjgpOmTDGUpzm8yRFMOAxc4DBo2mRAH2Dwzoasv9So8YxkZIkhEOLE/+EUQHywbMTq8S31kUBxCLqoGLPcfUiaTWklSy1KJKUe6FGClQp3W/ea0VdmN9eNDik6FCT5qk79nc1P5ZlHfJSjZDMNKP7wJ4xpvwlMWSNzLIuCQ6xVfSe5U3edgjdyJ17tJXiVjO8QlSa+O7nqDrEg/vgixfHGLCn87A7a1w/soZb41MNGjbvqgYPHtGWaq4A6IDkJ9bCzc5UKwc8XCAlqGYe5DrVc+bZFV3w1uYKGd+a802AnhAgMBAAECggEADMhL5SdHaRxHzO0yb9yArxyTNnfK1rr5ordyAgWoAjj3x7n6K2tb/hH2qLksUsOUouP0MIEao1nQ0dAv2domzo93JhFHdn0BQdu8jc4u114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yq37hAWr2GaXHWOJKXl/Dd4SL+7jeqQFg==";

    // 支付宝公钥,对应APPID下的支付宝公钥。
//    public String alipayPublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAgqtVJtH7Tbvp2KrhfqjudGkITrR2TC5+pmWxtpe9jKMo4KTpkwxlKc5vMkRTDgMXOAwaNpkQB9g8M6GrL/UqPGMZGSJIRDixP/hFEB8sGzE6vEt9ZFAcQi6qBiz3H1Imk1pJUstSiSlHuhRgpUKd1v3mtFXZjfXjQ4pOhQk+apO/Z3NT+WZR3yUo2QzDSj+8CeMab8JTFkjcyyLgkOsVX0nuVN3nYI3cide7SV4lYzvEJUmvju56g6xIP74IsXxxiwp/OwO2tcP7KGW+NTDRo276oGDx7RlmquAOiA5CfWws3OVCsHPFwgJahmHuQ61XPm2RVd8NbmChnfmvNNgJ4QIDAQAB";
    public String alipayPublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAkjwK/ULT3DiHCr314eZp2v7LfVixsu76fYab/vfPFBMaxVSTUzub7H2M4crtWUOPgkHdm9kT7VxeLeCmzKPuUaohnVCmfx1+Xhn419sVa7CYga7W42t5nahTLIgltJNm0JMFCKUMrlQwURjRTBXm9QMpnxD1nzyUNgoe0vTF+cidNnTmCqc+gu/oATDwOsMjfSBEzWt7G3JMM8fKKV0vnJLe3LSSQ/6PAaQyazgktWCJNXNbIgTbW8IoWGCD9e/p0lvBKjLCYSm0417YtsjCT7rcGoNEI5UV9vT5NFhWyhpZFwXTHm6hCy9HNqXwjseRzxLSt9EOB0XYeVag64ylfQIDAQAB";
    // 支付宝会悄悄的给我们发送一个请求，告诉我们支付成功的信息
//    public String notifyUrl = "http://doorbath.natapp1.cc/notify_url.html";
//    public String notifyUrl = "http://doorbath.natapp1.cc/alipay/alipay/notify";

    // 服务器异步通知页面路径  需http://格式的完整路径，不能加?id=123这类自定义参数，必须外网可以正常访问
    // 注意：每次重新启动ngrok，都需要根据实际情况修改这个配置
    public static String notifyUrl = "http://doorbath.natapp1.cc/alipay/notify";;

    //同步通知，支付成功，一般跳转到订单列表页
    public String returnUrl = "http://footbathdoor.com/center/list.html";
//    public String returnUrl = "http://doorbath.natapp1.cc/center/list.html";
//    public String returnUrl = "http://member.zyz.com/memberOrder.html";

    // 签名方式
    private String signType = "RSA2";

    // 字符编码格式
    private String charset = "utf-8";

    // 响应格式，默认也是json
    private String formatType = "json";

    //订单超时时间
    private String timeout = "1m";

    //这是沙箱接口路径,正式路径为https://openapi.alipay.com/gateway.do
    // 支付宝网关；https://openapi-sandbox.dl.alipaydev.com/gateway.do
    public String gatewayUrl = "https://openapi-sandbox.dl.alipaydev.com/gateway.do";
//    public String gatewayUrl = "https://openapi.alipay.com/gateway.do";

    /**
     * 支付
     * @param vo
     * @return
     * @throws AlipayApiException
     */
    public String pay(AlipayVO vo) throws
            AlipayApiException {
        //1、根据支付宝的配置生成一个支付客户端
        AlipayClient alipayClient = new
                DefaultAlipayClient(gatewayUrl,
                appId, merchantPrivateKey, formatType,
                charset, alipayPublicKey, signType);
        //2、创建一个支付请求，并设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(returnUrl);
        alipayRequest.setNotifyUrl(notifyUrl);

        //商户订单号,商户网站订单系统中唯一订单号,必填
        String orderSn = vo.getOutTradeNo();
        //TODO 支付金额,暂时用打赏金额代替,后期改
        String rewardPrice = vo.getTotalAmount();
        //订单名称,必填
        String subject = vo.getSubject();
        //商品描述.可空
        String body = vo.getBody();
        //设置主体内容
                alipayRequest.setBizContent(" {\"out_trade_no\":\"" + orderSn + "\","
                + "\"total_amount\":\"" + rewardPrice + "\","
                + "\"subject\":\"" + subject + "\","
                + "\"body\":\"" + body + "\","
                + "\"timeout_express\":\"" + timeout + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        //执行请求
        String result = alipayClient.pageExecute(alipayRequest).getBody();
        //会收到支付宝的响应，响应的是一个页面，只要浏览器显示这个页面，就会自动来到支付宝的收银台页面
        System.out.println("支付宝的响应：" + result);
        return result;
    }

    /**
     * 异步通知参数验签
     * @param notifyRequest 支付宝以post发过来的异步通知请求
     * @return
     */
    public boolean signVerify(HttpServletRequest notifyRequest) throws UnsupportedEncodingException, AlipayApiException {
        Map<String, String> params = new HashMap<>();
        Map<String, String[]> requestParams = notifyRequest.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = iter.next();
            String[] values = requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
             valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        //调用SDK验证签名
        return AlipaySignature.rsaCheckV1(params, alipayPublicKey, charset, signType);
    }
}
